import requests
import os
import base64
import matplotlib.pyplot as plt 
import matplotlib.image as mpimg

# 对本地图片进行base64编码
with open("./scene.jpg","rb") as f: # 转为二进制格式
    base64_data = str(base64.b64encode(f.read()), encoding = "utf-8") #使用base64进行加密

# 调用momodel上风格迁移的api，发送编码图片，在云端实现AI风格转换后，下载转换完后的base64图片
base_url = "https://momodel.cn/pyapi/apps/run/"
app_id = "5bfb634e1afd943c623dd9cf"
input_dic = {"输入图片": {"val": base64_data, "type": "base64_image"}, "选择风格": {"val": "印象派-星空", "type": "str"}}
output_dic = {"风格迁移后的图片": {"type": "base64_image"}}
app_version = "0-0-10"
payload = {"app": {"input": input_dic, "output": output_dic}, "version": app_version}
response = requests.post(base_url + app_id, json=payload)
tmp = response.json()

#将转换后的base64图片解码存储到本地
ai_img = base64.b64decode(bytes(tmp["response"]["风格迁移后的图片"], encoding = "utf-8"))
with open("./scene_style.jpg","wb") as f: # 转为二进制格式
    f.write(ai_img)

#显示转换前后照片
img_origin = mpimg.imread('scene.jpg')
img_style = mpimg.imread('scene_style.jpg')
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.imshow(img_origin)
ax2.imshow(img_style)
plt.show()
